<template>
  <div>
    <Title title="账号信息" style="margin-bottom: 16px;" />
    <div class="table-container">
      <PlainCreateBtn class="add-btn" @click="addItem">选择账号</PlainCreateBtn>
      <el-table
        :data="detailData.linkSignUp.accountsInfoList"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <EmptyPlaceholder slot="empty" mode="table" />
        <el-table-column label="账号名称" min-width="200" align="left">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.accountName" />
          </template>
        </el-table-column>
        <el-table-column label="平台" min-width="160" align="left">
          <template slot-scope="scope">
            <div class="flex-center">
              <PlatformIcon :data="scope.row.platformName" />
              <ToolTip :content="scope.row.platformName" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="账号ID" min-width="160" align="left">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.accountCode" />
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" min-width="160" align="left">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.supplierName" />
          </template>
        </el-table-column>
        <el-table-column label="签单签约经纪" min-width="160" align="left">
          <template slot-scope="scope">
            <CheckUserInfo :user-id="scope.row.agentId" :label="scope.row.agentName" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="80" align="left">
          <template slot-scope="scope">
            <div class="button-text" @click="deleteItem(scope.$index)">删除</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <AccountSelection
      ref="AccountSelectionRef"
      :visible.sync="drawerVisible"
      :multiple="true"
      :expand-params = "{
        signDetailStatus: '1,2,5,6',
        excludeTerminating: true
      }"
      :expend-filter="[{ keyword: 'operator', name: '供应商名称', type: 'input', labelWidth: '99px' }]"
      @submit="handleAccount" >
      <template slot="tableColumn">
        <AccountColumn />
      </template>
    </AccountSelection>
  </div>
</template>

<script>
import Title from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import PlatformIcon from '@/components/Common/platformIcon';
import AccountSelection from '@/components/resource/AccountSelection';
import AccountColumn from './AccountColumn';
// API
import { getResouceInfo } from '@/api/resource';

export default {
  components: { Title, selectWithUserLoad, EmptyPlaceholder, PlatformIcon, AccountSelection, AccountColumn },
  filters: {
    formatSignStatus(val) {
      return {
        0: '未签约',
        1: '已签约',
        [-1]: '已解约'
      }[val];
    },
    signStatusColor(val) {
      return {
        0: '#31CC9C', // '未签约'
        1: '#406EFF', // '已签约'
        [-1]: '#FD8546' // '已解约'
      }[val];
    }
  },
  model: {
    prop: 'detailData',
    event: 'changeData'
  },
  props: {
    detailData: {
      type: Object,
      default: () => { return {}; }
    },
    labelWidth: {
      type: String,
      default: '90px'
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    colSpan: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      formRules: {
        id: [{ required: true, trigger: 'change', message: '请选择审批单号' }]
      },
      showRelated: false,
      drawerVisible: false
    };
  },
  created() {
    const mediumId = Number(this.$route.query.mediumId);
    const routerName = this.$route.name;
    if (routerName === 'terminationCreate' && mediumId) {
      this.linkResourceChange(mediumId);
    }
  },
  methods: {
    linkResourceChange(mediumId) {
      if (!mediumId) return;
      getResouceInfo(mediumId, {}).then(res => {
        if (res.data) {
          const data = res.data;
          const result = {
            id: mediumId,
            accountName: data.resourceName,
            accountCode: data.resourceId,
            platformName: data.platformTypeName,
            agentName: data.additionalKey.contractBroker,
            agentId: data.additionalKey.contractBrokerId,
            signStatus: data.signStatus,
            supplierName: data.cooperation,
            supplierId: data.supplierId
          };
          this.$set(this.detailData.linkSignUp, 'accountsInfoList', [result]);
        }
      });
    },
    handleAccount(data) {
      this.drawerVisible = false;
      const result = data.map(i => {
        return this.keyTranslate(i);
      });
      this.$set(this.detailData.linkSignUp, 'accountsInfoList', _.cloneDeep(result));
    },
    addItem() {
      this.drawerVisible = true;
      const accountsInfoList = this.detailData.linkSignUp.accountsInfoList;
      if (accountsInfoList && accountsInfoList.length) {
        const cloneAccounts = _.cloneDeep(accountsInfoList).map(i => {
          return this.keyTranslate(i, true);
        });
        this.$refs.AccountSelectionRef.init(cloneAccounts);
      } else {
        this.$refs.AccountSelectionRef.init([]);
      }
    },
    deleteItem(index) {
      this.detailData.linkSignUp.accountsInfoList.splice(index, 1);
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        const list = this.detailData.linkSignUp.accountsInfoList.filter(i => i.id);
        if (list.length === 0) {
          reject('请选择账号');
          return;
        }
        resolve(true);
      });
    },
    /**
     * 因为资源列表的字段格式和签约内审的不一样，所以需要转换一下
     *  isReverse: false: 资源列表 -> 签约内审  true: 签约内审 -> 资源列表
     */
    keyTranslate(data, isReverse = false) {
      if (!isReverse) {
        /** 资源的签约状态 signDetailStatus
          0: '未签约',
          1: '待签合同',
          2: '已签约',
          3: '协商解约',
          4: '到期解约',
          5: '已续约',
          6: '自动续约',
          7: '已解约'
          签约内审的签约状态 signDetailStatus
          0: '未签约',
          1: '已签约',
          [-1]: '已解约'
         */
        let signStatus = 0;
        if ([2, 5, 6].includes(data.signDetailStatus)) {
          signStatus = 1;
        } else if ([3, 4, 7].includes(data.signDetailStatus)) {
          signStatus = -1;
        }
        return {
          id: data.mediumId,
          accountName: data.baseInfo.accountName,
          accountCode: data.baseInfo.accountId,
          platformName: data.platformTypeName,
          agentName: data.additionalKey.contractBroker,
          agentId: data.additionalKey.contractBrokerId,
          signStatus: signStatus,
          supplierName: data.cooperation,
          supplierId: data.supplierId,
          originData: JSON.stringify(data)
        };
      } else {
        const originData = this.jsonParse(data.originData);
        if (originData) return originData;
        return {
          mediumId: data.id,
          platformTypeName: data.platformName,
          cooperation: data.supplierName,
          supplierId: data.supplierId,
          baseInfo: {
            accountName: data.accountName,
            accountId: data.accountCode
          },
          additionalKey: {
            contractBroker: data.agentName,
            contractBrokerId: data.agentId
          }
        };
      }
    },
    jsonParse(obj) {
      if (!obj) return null;
      try {
        return JSON.parse(obj);
      } catch (error) {
        return null;
      }
    }
  }
};
</script>

<style lang="scss" scoped>

.table-container {
  position: relative;
  margin-top: 10px;
  .add-btn {
    position: absolute;
    right: 0;
    top: -44px;
  }
}
</style>
